package com.xiemu.ironman.core.service.impl;

import com.xiemu.ironman.core.utils.DeployUtils;
import com.xiemu.ironman.sdk.Calculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;


@Service("eDsImpl")
public class ReflectHotDeployServiceImpl  extends AbstractHotDeployServiceImpl{


    @Autowired
    ApplicationContext applicationContext;

    @Value("${hot.deploy.jar.file.path}")
    private String jarAddress;

    public ReflectHotDeployServiceImpl(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    /**
     * 热加载Calculator接口的实现 反射方式
     *
     * @jarName xx.jar
     * @implClassName com.xiemu.ironman.sdk.adaptor.CalculatorImpl
     */
    public void hotDeploy(String jarName, String implClassName)  {

        Class clazz = null;
        try {
            URLClassLoader urlClassLoader =
                    new URLClassLoader(
                            new URL[] {new URL(DeployUtils.getJarPth(jarAddress, jarName))},
                            Thread.currentThread().getContextClassLoader());
            clazz = urlClassLoader.loadClass(implClassName);
            Calculator calculator = (Calculator) clazz.newInstance();
            int result = calculator.add(1, 2);
            System.out.println(result);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public void deletejar(String jarName) {
        String jarPth = DeployUtils.getJarPth(jarAddress, jarName);
        try {
            super.delete(jarName,jarPth);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
